package com.ming.sportdemo.Aop;

import com.ming.sportdemo.annotation.NeedFinalRole;
import com.ming.sportdemo.annotation.NeedRole;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Repository;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URLDecoder;

@Aspect
@Repository
public class RoleAop {
/*    @Pointcut("@annotation(com.ming.sportdemo.annotation.NeedRole)")
    public void role(){
    }

    @Pointcut("@annotation(com.ming.sportdemo.annotation.NeedFinalRole)")
    public void finalRole(){

    }
    @Around("role()||finalRole()")*/
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        HttpServletRequest request = (HttpServletRequest) args[0];
        String role = URLDecoder.decode(request.getHeader("role"),"UTF-8");
        Object proceed = null;
        Class cl = joinPoint.getTarget().getClass();
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = cl.getDeclaredMethod(methodSignature.getName(),methodSignature.getParameterTypes());
        NeedRole needRole = method.getAnnotation(NeedRole.class);
        NeedFinalRole needFinalRole = method.getAnnotation(NeedFinalRole.class);
        if(needRole!=null){
            if(role.equals("管理员")||role.equals("超级管理员")){
                System.out.println("role验证成功");
                proceed = joinPoint.proceed();
                return proceed;
            }else {
                System.out.println("验证失败");
                return null;
            }
        }
        if(needFinalRole!=null){
            if(role.equals("超级管理员")){
                System.out.println("finalrole验证成功");
                proceed = joinPoint.proceed();
                return proceed;
            }else {
                System.out.println("final验证失败");
                return null;
            }
        }
        //proceed = joinPoint.proceed();
        return proceed;
    }
}
